import pandas as pd
from scipy import stats


def do_analysis(df: pd.DataFrame):
    """
    计算相关性
    :param df:
    :return:
    """

    def process_nan(value):
        if isinstance(value, float) and value != value:
            return None  # 替换 NaN 值为 None 或其他值
        elif isinstance(value, dict):
            return {k: process_nan(v) for k, v in value.items()}
        elif isinstance(value, list):
            return [process_nan(v) for v in value]
        else:
            return value

    def get_result(obj: pd.DataFrame) -> []:
        """
        获取前端需要的结结构
        :param obj:
        :return:
        """
        output = []
        for index, row in obj.iterrows():
            output.append({'row_key': str(index), 'values': {str(col): process_nan(row[col]) for col in obj.columns}})
        return output

    item = df.corr(method='pearson')
    return get_result(item)


class Correction(object):
    def __init__(self, df):
        self.df = df

    def calculate_p(self) -> []:
        df = self.df
        output = []
        # 计算相关性
        # p_values = {}
        # 遍历相关性矩阵的行和列
        item = df.corr(method='pearson')
        for row_key in item.columns:
            values = {}
            for column_key in item.columns:
                if row_key != column_key:
                    correlation, p_value = stats.pearsonr(df[row_key], df[column_key])
                    # final_value = str(round(item[row_key][column_key], 3))
                    final_value = "{:.3f}".format(item[row_key][column_key])
                    # p_values[(row_key, column_key)] = p_value
                    if p_value <= 0.01:
                        final_value += '**'
                    elif p_value <= 0.05:
                        final_value += '*'
                    values[column_key] = final_value
                else:
                    # values[column_key] = round(item[row_key][column_key], 3)
                    values[column_key] = "{:.3f}".format(item[row_key][column_key])
            # 将结果添加到输出数据结构中
            output.append({"row_key": row_key, "values": values, })
        # # 打印显著性结果
        # for (column1, column2), p_value in p_values.items():
        #     if p_value < 0.05:
        #         print(f"Correlation between {column1} and {column2} is significant.")
        return output
